package com.ebelter.myehc.models.managers;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.bluetooth.base.BaseManager;
import com.ebelter.btcomlib.models.bluetooth.base.BlueScan;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.bean.SleepQuality;
import com.ebelter.btcomlib.models.bluetooth.bean.SleepUnit;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IConnectStationCallback;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IScanCallback;
import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.BOManager;
import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.bean.BOMesureResultBean;
import com.ebelter.btcomlib.models.bluetooth.products.bloodoxgen.interfaces.BOMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.BpmManager;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.bean.BpmMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.bpm.interfaces.BPMMeasureCallback;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.BraceletManager;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb_Table;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.RateBean;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.WalkBean;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.interfaces.BraceletMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.EarTemperatureManager;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.bean.EarTemMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.ear_temperature.interfaces.EarTemperatureMesureResult;
import com.ebelter.btcomlib.models.bluetooth.products.scale.ScaleManager;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult;
import com.ebelter.btcomlib.models.bluetooth.products.scale.interfaces.IScaleMeasureCallback;
import com.ebelter.btcomlib.models.bluetooth.products.temperature.TemperatureManager;
import com.ebelter.btcomlib.models.bluetooth.products.three2one.ThreeOneManager;
import com.ebelter.btcomlib.models.bluetooth.products.three2one.bean.ThreeOneMesureResultBean;
import com.ebelter.btcomlib.models.bluetooth.products.three2one.interfaces.ThreeOneMesureResult;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.ThreadManager;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.myehc.beans.BraTodayData;
import com.ebelter.myehc.beans.StepOneHourInfoAdapterBean;
import com.ebelter.myehc.models.http.request.EhcNetUtils;
import com.ebelter.myehc.models.http.response.others.GetNewestBraHeartTime_R;
import com.ebelter.myehc.ui.activitys.MainActivity;
import com.raizlabs.android.dbflow.sql.language.Select;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Ehc的设备管理器
 */
public class EhcManager extends BaseHandle {


    public static final String TAG = "EhcManager";


    private Context mContext;
    /**
     * 当前需要连接的设备
     */
    private ProductStyle curRunProductStyle = ProductStyle.NO;
    /**
     * 当前需要连接的设备
     */
    //private BluetoothDevice device;


    //蓝牙扫描器
    private BlueScan mBlueScan;
    private BaseManager mBaseManager;   //也是当前连接的manager

    private BpmManager mBpmManager;     //血压计管理器
    private BOManager mBOManager;       //血氧管理器
    public  BraceletManager mBracetManager;//手环管理器
    private EarTemperatureManager mEarTemperatureManager;   //耳温枪管理器
    private ScaleManager mScaleManager;                     //体脂秤管理器
    private ThreeOneManager mThreeOneManager;               //三合一管理器

    public boolean isOtaUpdate;
    private void restartInitBlueScan(){
        if (mBlueScan != null){
            mBlueScan.realse();
            mBlueScan = null;
        }
        mBlueScan = new BlueScan(mContext);
    }

    //退出释放
    public void exit() {
        //01 释放蓝牙扫描器
        if (mBlueScan != null) {
            if (mBlueScan.isScaningFlag) {
                mBlueScan.stopScanBluetoothDevices();
            }
            mBlueScan = null;
        }
        stopAutoCheck();

        mBaseManager.exit();
        mBpmManager.exit();
        mBOManager.exit();
        mBracetManager.exit();
        mEarTemperatureManager.exit();
        mScaleManager.exit();
        mThreeOneManager.exit();

        mBaseManager = null;
        mBpmManager = null;
        mBOManager = null;
        mBracetManager = null;
        mEarTemperatureManager = null;
        mScaleManager = null;
        mThreeOneManager = null;
    }


    public EhcManager(Context context) {
        super(context);
        init(context);
    }

    //初始化各个产品
    private void init(Context context) {
        this.mContext = context;
        //restartInitBlueScan();
        mBlueScan=new BlueScan(mContext);
        mBpmManager = new BpmManager(context);
        mBOManager = new BOManager(context);
        mBracetManager = new BraceletManager(context);
        mEarTemperatureManager = new EarTemperatureManager(context);
        mScaleManager = new ScaleManager(context,200);
        mThreeOneManager = new ThreeOneManager(context);

        setListeners();
    }

    //设置更种监听器
    private void setListeners() {

        //血压计测量结果回调
        mBpmManager.setBpmMeasureCallback(new BPMMeasureCallback() {
            @Override
            public void dynamicSystolicPressure(int value) {
                LogUtils.i(TAG, "---血压计mBpmManager--dynamicSystolicPressure--value = " + value);
                if (mesuresCalBack != null) mesuresCalBack.BPM_dynamicSystolicPressure(value);
            }

            @Override
            public void measureError(String connectName,int errorType) {
                LogUtils.i(TAG, "---血压计mBpmManager--measureError--errorType = " + errorType);
                if (mesuresCalBack != null) mesuresCalBack.BPM_measureError(connectName,errorType);
            }

            @Override
            public void measureResult(BpmMesureResult mesureResult) {
                LogUtils.i(TAG, "---血压计mBpmManager--measureResult--" + mesureResult.toString());
                if (mBpmManager != null) mBpmManager.sendReceiveSuccessACK();
                if (mesuresCalBack != null) mesuresCalBack.BPM_measureResult(mesureResult);
            }
        });

        //血氧测量结果回调
        mBOManager.setBoMeasureCallback(new BOMesureResult() {
            @Override
            public void mesureing(int value) {
                LogUtils.i(TAG, "---血氧mBOManager--mesureing--value = " + value);
                if (mesuresCalBack != null) mesuresCalBack.BO_mesureing(value);
            }

            @Override
            public void mesureResult(BOMesureResultBean resultBean) {
                LogUtils.i(TAG, "---血氧mBOManager--mesureResult--resultBean = " + resultBean.toString());
                if (mesuresCalBack != null) mesuresCalBack.BO_mesureResult(resultBean);
            }
        });

        //耳温枪测量结果回调
        mEarTemperatureManager.setEarTemperatureMeasureCallback(new EarTemperatureMesureResult() {
            @Override
            public void mesureResult(EarTemMesureResult result) {
                LogUtils.i(TAG, "---耳温枪mEarTemperatureManager--mesureResult--resultBean = " + result.toString());
                mEarTemperatureManager.sendReceiveSuccessACK();
                if (mesuresCalBack != null) mesuresCalBack.ET_mesureResult(result);


            }

            @Override
            public void error(int errorCode) {
                LogUtils.i(TAG, "---耳温枪mEarTemperatureManager--error--errorCode = " + errorCode);
                if (mesuresCalBack != null) mesuresCalBack.ET_error(errorCode);
            }

            @Override
            public void onDevicePoweroff() {
                LogUtils.i(TAG, "---耳温枪mEarTemperatureManager--onDevicePoweroff--resultBean");
                if (mesuresCalBack != null) mesuresCalBack.ET_onDevicePoweroff();
            }
        });


        //体脂秤测量结果回调
        mScaleManager.setmIMeasureResultCallback(new IScaleMeasureCallback() {
            @Override
            public void onReceiveMeasureResult(ScaleMeasureResult result) {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onReceiveMeasureResult--result" + result.toString());
                if (mScaleManager != null) {
                    mScaleManager.sendMesureDataACK();//发送一个接收到测量结果的ack
                    ScaleUser.getUser().setImpedance(result.getResistance());
                    ScaleUser.getUser().setWeight(result.getWeight());
                    mScaleManager.sendUserInfo(ScaleUser.getUser());//下发一次用户信息
                }
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onReceiveMeasureResult(result);
            }

            @Override
            public void onReceivedynamicMeasureResult(ScaleMeasureResult result) {

            }

            @Override
            public void onWeightOverLoad() {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onWeightOverLoad--result");
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onWeightOverLoad();
            }

            @Override
            public void onReceiveHistoryRecord(ScaleMeasureResult result) {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onReceiveHistoryRecord--result = " + result.toString());
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onReceiveHistoryRecord(result);

                if (mScaleManager != null) {//获取到历史数据回应一个ack过去 直到没有离线数据会执行onHistoryDownloadDone方法
                    mScaleManager.sendGetHistoryDataACK();
                }
            }

            @Override
            public void onFatMeasureError(int type) {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onFatMeasureError--type = " + type);
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onFatMeasureError(type);
            }

            @Override
            public void onHistoryDownloadDone() {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onHistoryDownloadDone--");
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onHistoryDownloadDone();
            }

            @Override
            public void unitChange(String unit) {
                LogUtils.i(TAG, "---体脂秤mScaleManager--unitChange--unit = " + unit);
            }

            @Override
            public void onLowPower() {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onLowPower--");
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onLowPower();
            }

            @Override
            public void setUserInfoSuccess() {
                LogUtils.i(TAG, "---体脂秤mScaleManager--setUserInfoSuccess--");
                 if (mScaleManager!=null)mScaleManager.setSleepDisconnectTime(2);
            }

            @Override
            public void receiveTime(long time) {
                LogUtils.i(TAG, "---体脂秤mScaleManager--receiveTime--" + TimeUtils.formatTime1(time));
                if (mesuresCalBack != null) mesuresCalBack.SCALE_receiveTime(time);

                //--------第二步：接收到同步时间以后 下发用户信息
                if (mScaleManager != null) mScaleManager.sendUserInfo(ScaleUser.getUser());


            }

            @Override
            public void onScaleWake() {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onScaleWake--");
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onScaleWake();

                //---------第一步：唤醒的第一步是同步时钟
                if (mScaleManager != null) mScaleManager.syncSystemClock();

            }

            @Override
            public void onScaleSleep() {
                LogUtils.i(TAG, "---体脂秤mScaleManager--onScaleSleep--");
                if (mesuresCalBack != null) mesuresCalBack.SCALE_onScaleSleep();

                //休眠以后去获取离线数据
                if (!NetUtils.available()) {//当网络可以用的时候才去请求离线数据，因为请求回来要立即上传的
                    return;
                }
                if (mScaleManager != null) {
                    ScaleUser user = ScaleUser.getUser();
                    if (!TextUtils.isEmpty(user.getBtId()) && !TextUtils.equals("0", user.getBtId())) {//此时的用户btid是正确的并且不是访客
                        LogUtils.i(TAG, "--------尝试请求历史数据---user.getBtId()=" + user.getBtId());
                        mScaleManager.sendGetHistoryDataRequest(user.getBtId());
                    }
                }

            }

            @Override
            public void dealScaleResponse(int cmd, int position) {

            }
        });


        //三合一测量结果回调
        mThreeOneManager.setThreeOneMeasureCallback(new ThreeOneMesureResult() {
            @Override
            public void error(int errorCode) {
                LogUtils.i(TAG, "---三合一mThreeOneManager--error--errorCode = " + errorCode);
                if (mesuresCalBack != null) mesuresCalBack.ThreeOne_error(errorCode);
            }

            @Override
            public void mesureResult(ThreeOneMesureResultBean mesureResult) {
                LogUtils.i(TAG, "---三合一mThreeOneManager--mesureResult--" + mesureResult.toString());
                if (mesuresCalBack != null) mesuresCalBack.ThreeOne_mesureResult(mesureResult);
            }
        });


        //手环
        mBracetManager.setmBraceletMesureResult(new BraceletMesureResult() {
            @Override
            public void sysTimeSuccess() {
                LogUtils.i(TAG, "手环同步时间成功");//第一步完成
                getShHVersion();//第二步 获取版本信息
                closeNotifications();//关闭消息通知
            }

            @Override
            public void version(String version) {
                LogUtils.i(TAG, "手环版本号信息:"+version);//第二步完成
                mBracetManager.version = version;
                sendBraUserInfo();//第三步 下发用户信息
            }
            @Override
            public void setUserInfoSuccess() {//第二步 下发用户信息 完成
                LogUtils.i(TAG, "手环设置用户信息成功");

                if (mesuresCalBack != null) mesuresCalBack.Bra_setUserSuccess();

                getNewestBraHeartTime();//获取最新的心率时间 为计算从哪个时间段开始同步数据

            }

            @Override
            public void setXlCycSuccess() {
                LogUtils.i(TAG, "手环设置心率周期成功");
                if (mesuresCalBack != null) mesuresCalBack.Bra_setXlCycSuccess();

                startJianTingShHData();//开始获取手环的实时数据

            }

            @Override
            public void sysHistoryDataFinish() {
                LogUtils.i(TAG, "手环同步历史数据结束");
                queryOneDayDate();//查询今天的统计数据 比如步数 心率 睡眠显示在界面上
                if (mesuresCalBack != null) mesuresCalBack.sysHistoryDataFinish();
            }

            @Override
            public void getRealTimeData(WalkBean obj) {
                LogUtils.i(TAG, "手环获取实时数据成功:" + obj.toString());
                if (mesuresCalBack != null) mesuresCalBack.getRealTimeData(obj);
            }

            @Override
            public void getRealTimeXlData(RateBean obj) {
                LogUtils.i(TAG, "手环获取心率实时数据成功:" + obj.toString());
                if (mesuresCalBack != null) mesuresCalBack.getRealTimeXlData(obj);

              //  mBracetManager.getVersion();//下发版本信息
            }

            @Override
            public void openOtaSuccess() {
                LogUtils.i(TAG, "手环OtaSuccess");
                if (mesuresCalBack != null) mesuresCalBack.SHH_open_ota_success();
            }

            @Override
            public void lowpower() {
                LogUtils.i(TAG, "手环lowpower");
                if (mesuresCalBack != null) mesuresCalBack.SHH_lowpower();
            }




        });
    }

    //关闭消息通知
    private void closeNotifications() {
        if (mBracetManager!=null){
            mBracetManager.closeNotifications();
        }
    }


    //获取最新的心率时间
    private void getNewestBraHeartTime() {

        if (NetUtils.available()){
           //网络可用
            LogUtils.i(TAG,"网络可用");

            EhcNetUtils.getInstance().getNewestBraHeartTime(this, MainActivity.getAuthKey(), new HttpResponse<GetNewestBraHeartTime_R>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, GetNewestBraHeartTime_R getNewestBraHeartTime_r, String s) {
                    LogUtils.i(TAG,"EhcManager--getNewestBraHeartTime获取最新心跳时间 -- s = " + s);


                    String time = null;
                    if (isRequestSuccess&&getNewestBraHeartTime_r!=null&&getNewestBraHeartTime_r.resultData!=null&&!TextUtils.isEmpty(getNewestBraHeartTime_r.resultData.getTime())){
                        time=getNewestBraHeartTime_r.resultData.getTime();
                    }

                    LogUtils.i(TAG,"最终的最新心跳时间 -- time = " + time);
                    if (mBracetManager != null) mBracetManager.sysHistoryData2(time);//同步历史数据  zcq
                    //if (mBracetManager != null) mBracetManager.sysHistoryData2(null);//同步历史数据

                }
            });



        }else {
            LogUtils.i(TAG,"网络不可用");
            //网络不可用
            if (mBracetManager != null) mBracetManager.sysHistoryData2(null);//同步历史数据
        }

    }


    public void sendUserInfo2Scale() {
        if (mScaleManager != null && mScaleManager.isConnect())
            mScaleManager.sendUserInfo(ScaleUser.getUser());
    }


    private void sendBraUserInfo() {
        if (mBracetManager != null) {
            int height = ScaleUser.getUser().getHeight();
            int weight = NumUtils.numBaoLiuWei0(ScaleUser.getUser().getWeight());
            int sex;//手环的性别是0女1男
            if (ScaleUser.getUser().getSex() == 0) {
                sex = 1;
            } else {
                sex = 0;
            }
            LogUtils.i(TAG, "---下发的用户信息height=" + height + "----weight=" + weight + "---sex=" + sex);
            mBracetManager.setUserInfo(height, weight, sex);
        }
    }

    //开始每隔多少一段时间去获取实时数据
    private void startJianTingShHData() {
        removeMessages(what_GetShH_RealTime_data);
        sendEmptyMessage(what_GetShH_RealTime_data);
    }

    private void stopJianTingShHData() {
        removeMessages(what_GetShH_RealTime_data);
    }


    //查询今天的数据
    public void queryOneDayDate() {


        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {

                long cT = System.currentTimeMillis();//当前时间

                String today = TimeUtils.formatTime14(cT);//yyMMdd  190314
                String yesterday = TimeUtils.formatTime14(cT - 24 * 3600000);//yyMMdd 190313

                long yesterDaystartStr = Long.parseLong(yesterday + "0000");  //1903130000
                long startStr = Long.parseLong(today + "0000"); //1903140000
                long endStr = Long.parseLong(today + "2350");//1903142350


                //查询到今天的数据
                List<BraDb> todayDbList = new Select().from(BraDb.class)
                        .where(BraDb_Table.timeStr.greaterThanOrEq(startStr))
                        .and(BraDb_Table.timeStr.lessThanOrEq(endStr))
                        .orderBy(BraDb_Table.timeStr, true).queryList();

                //查询到今天和昨天的所有数据
                List<BraDb> yesterdayDbList = new Select().from(BraDb.class)
                        .where(BraDb_Table.timeStr.greaterThanOrEq(yesterDaystartStr))
                        .and(BraDb_Table.timeStr.lessThanOrEq(endStr))
                        .orderBy(BraDb_Table.timeStr, true).queryList();

                int _6Steps = 0;//前6小时的总步数
                int _12Steps = 0;
                int _18Steps = 0;
                int _24Steps = 0;



                int maxHeart = 0;//最大心率
                int minHeart = 0;
                int avgHeart = 0;

                int heartCount = 0;//心率的有效条数 为了计算平均值的
                int heartTotal = 0;//心率总数
                ArrayList<RateBean> list2_xl = new ArrayList<>();//心率集合


                float stride ; //步幅 cm
                float stepCaruli ; //卡路里
                //  能量：每步能量 = （体重(kg)-15）X0.000693+0.005895


                long todayDateLong = TimeUtils.parseFormatter15Time(startStr + "").getTime();//今天时间0点0分的毫秒数
                ScaleUser user = ScaleUser.getUser();


                //0男1女
                stride = (float) (((user.getSex() == 1 ? user.getHeight() * 0.413 : user.getHeight() * 0.415) * 1.0 / 100));//这样做是为了取最新的步幅
                int weight = NumUtils.numBaoLiuWei0(user.getWeight()) - 15;
                stepCaruli = NumUtils.numBaoLiuWei6(weight * 0.000693 + 0.005895);//取最新的每步消耗的卡路里
                if (stepCaruli < 0) {
                    stepCaruli = 0;
                }


                int lastHour = getLastDatHour(todayDbList);
                int nowHour = new Date().getHours();//当前小时

                LogUtils.i(TAG, "---lastHour = "+lastHour+"---nowHour = "+nowHour);

                for (BraDb braDb : todayDbList) {
                    LogUtils.i(TAG, "今天-" + braDb.toString());
                    //今天-BraDb{id=147, timeStr=1809130020, dateType=1, step=0, weight=0, sex=1, height=162, heart=0, heart1=0, heart2=0, heart3=63}


                    Date date = TimeUtils.parseFormatter15Time(braDb.timeStr + "");//当前项的记录时间
                    long time = date.getTime();
                    int h = date.getHours();//当前项纪录的小时

                    LogUtils.i(TAG, "当前解析的时间-" + braDb.timeStr+"--- h = "+h);

                    long cTl = (time - todayDateLong) / 1000;


                    if (h!=nowHour){
                        if (h < 6) {
                            _6Steps += braDb.step;
                            LogUtils.i(TAG, "h="+h+"当前的时间步数是_6Steps="+_6Steps);
                        } else if (h >= 6 && h < 12) {
                            _12Steps += braDb.step;
                            LogUtils.i(TAG, "h="+h+"当前的时间步数是_12Steps="+_12Steps);
                        } else if (h >= 12 && h < 18) {
                            _18Steps += braDb.step;
                            LogUtils.i(TAG, "h="+h+"当前的时间步数是_18Steps="+_18Steps);
                        } else if (h >= 18 && h < 24) {
                            _24Steps += braDb.step;
                            LogUtils.i(TAG, "h="+h+"当前的时间步数是_24Steps="+_24Steps);
                        }
                    }

                    //心率值大于0说明就是有效的
                    if (braDb.heart > 0) {
                        heartCount++;
                        heartTotal = braDb.heart + heartTotal;
                        if (braDb.heart > maxHeart) {
                            maxHeart = braDb.heart;
                        }//150是十分钟的第0部分
                        if (braDb.heart < minHeart || minHeart == 0) {
                            minHeart = braDb.heart;
                        }
                        RateBean rateBean = new RateBean(cTl, braDb.heart);
                        list2_xl.add(rateBean);

                    }
                    if (braDb.heart1 > 0) {
                        heartCount++;
                        heartTotal = braDb.heart1 + heartTotal;
                        if (braDb.heart1 > maxHeart) {
                            maxHeart = braDb.heart1;
                        }
                        if (braDb.heart1 < minHeart || minHeart == 0) {
                            minHeart = braDb.heart1;
                        }
                        RateBean rateBean = new RateBean(cTl + 150, braDb.heart1);//150是十分钟的第一部分
                        list2_xl.add(rateBean);
                    }
                    if (braDb.heart2 > 0) {
                        heartCount++;
                        heartTotal = braDb.heart2 + heartTotal;
                        if (braDb.heart2 > maxHeart) {
                            maxHeart = braDb.heart2;
                        }
                        if (braDb.heart2 < minHeart || minHeart == 0) {
                            minHeart = braDb.heart2;
                        }
                        RateBean rateBean = new RateBean(cTl + 300, braDb.heart2);//300是十分钟的第二部分
                        list2_xl.add(rateBean);
                    }
                    if (braDb.heart3 > 0) {
                        heartCount++;
                        heartTotal = braDb.heart3 + heartTotal;
                        if (braDb.heart3 > maxHeart) {
                            maxHeart = braDb.heart3;
                        }//300是十分钟的第三部分
                        if (braDb.heart3 < minHeart || minHeart == 0) {
                            minHeart = braDb.heart3;
                        }
                        RateBean rateBean = new RateBean(cTl + 450, braDb.heart3);
                        list2_xl.add(rateBean);
                    }
                }


                int deepSleep = 0; //深眠 以分钟数为准
                int shallowSleep = 0;//浅眠
                int sleeplessness = 0;//清醒

                long starSleepTime = 0;//开始睡眠时间
                long endSleepTime = cT;//结束睡眠时间 默认为现在
                List<SleepUnit> list3_shm = new ArrayList<>();//睡眠时间


                boolean isStartSleepFlag = false;
                for (int i = 0; i < yesterdayDbList.size(); i++) {//-------------遍历所有昨天和今天的数据集合
                    BraDb yester = yesterdayDbList.get(i);
                    LogUtils.i(TAG, "昨天今天-" + yester.toString());

                    if (yester.dateType==0x0 || yester.dateType==0x1){
                        continue;
                    }

                    Date date = TimeUtils.parseFormatter15Time(yester.timeStr + "");//当前项的记录时间 yyMMddHHmm
                    long time = date.getTime();


                    if (yester.dateType == 0x11) {//0x11 为开始睡眠
                        starSleepTime = time; //记录一下当前的开始睡眠时间
                        isStartSleepFlag = true;
                        //  endSleepTime=time+600000;
                        deepSleep = 0; //在这两天的集合中当遇到开始睡眠时间 深眠 浅眠 清醒的总时间清零
                        shallowSleep = 0;
                        sleeplessness = 0;
                        list3_shm.clear();


                        //开始睡眠和结束睡眠为清醒状态
                        sleeplessness = sleeplessness + 10; //清醒的总时间加10分钟
                        SleepUnit sleepUnit = new SleepUnit(10, SleepQuality.Sleeplessness);
                        list3_shm.add(sleepUnit);


                    } else if (yester.dateType == 0x12) {//0x12 为清醒状态

                        sleeplessness = sleeplessness + 10; //清醒的总时间加10分钟
                        SleepUnit sleepUnit = new SleepUnit(10, SleepQuality.Sleeplessness);
                        list3_shm.add(sleepUnit);

                    } else if (yester.dateType == 0x13) {// 0x13 为浅睡状态

                        if (!isStartSleepFlag){
                            starSleepTime = time; //记录一下当前的开始睡眠时间
                            isStartSleepFlag = true;
                            //  endSleepTime=time+600000;
                            deepSleep = 0; //在这两天的集合中当遇到开始睡眠时间 深眠 浅眠 清醒的总时间清零
                            shallowSleep = 0;
                            sleeplessness = 0;
                            list3_shm.clear();
                        }
                        shallowSleep = shallowSleep + 10;//浅眠的总时间加10分钟
                        SleepUnit sleepUnit = new SleepUnit(10, SleepQuality.ShallowSleep);
                        list3_shm.add(sleepUnit);

                    } else if (yester.dateType == 0x14) {//0x14 为深睡状态
                        if (!isStartSleepFlag){
                            starSleepTime = time; //记录一下当前的开始睡眠时间
                            isStartSleepFlag = true;
                            //  endSleepTime=time+600000;
                            deepSleep = 0; //在这两天的集合中当遇到开始睡眠时间 深眠 浅眠 清醒的总时间清零
                            shallowSleep = 0;
                            sleeplessness = 0;
                            list3_shm.clear();
                        }
                        deepSleep = deepSleep + 10;//深眠的的总时间加10分钟
                        SleepUnit sleepUnit = new SleepUnit(10, SleepQuality.DeepSleep);
                        list3_shm.add(sleepUnit);

                    } else if (yester.dateType == 0x15) {//0x15 为结束睡眠
                        endSleepTime = time + 10 * 60000;//记录一下醒来的时间
                        sleeplessness = sleeplessness + 10;//清醒的总时间加10分钟
                        SleepUnit sleepUnit = new SleepUnit(10, SleepQuality.Sleeplessness);
                        list3_shm.add(sleepUnit);

                        int todayDateFromDb = date.getDay();
                        int todayDateFromPhone = new Date().getDay();
                        if (todayDateFromDb != todayDateFromPhone) {//此处判断结束睡眠的时间一定要是今天的 不然时间是有误的 做统计的清空处理
                            starSleepTime = 0;
                            LogUtils.i(TAG, "统计睡眠时间时--结束睡眠不是本天的日期 数据作废处理");
                        }

                    }

                }


                if (heartCount > 0) {
                    avgHeart = (int) (heartTotal * 1.0 / heartCount);
                }
                LogUtils.i(TAG, "心率总结：maxHeart=" + maxHeart + "---minHeart=" + minHeart + "---avgHeart=" + avgHeart + "--heartCount=" + heartCount + "---heartTotal=" + heartTotal);

                ArrayList<StepOneHourInfoAdapterBean> list1_steps = new ArrayList<>();//步数
                String tempTime = TimeUtils.formatTime11(System.currentTimeMillis());

                if (_6Steps > 0) {
                    StepOneHourInfoAdapterBean b = new StepOneHourInfoAdapterBean();
                    b.steps = _6Steps;
                    b.distances = _6Steps * stride;
                    b.carul = NumUtils.numBaoLiuWei0(_6Steps * stepCaruli);

                    String disT = tempTime;
                    if (lastHour >= 6){
                        disT=disT+" 0:00 - 6:00";
                    }else {
                        if (nowHour>=6){
                            disT=disT+" 0:00 - 6:00";
                        }else {
                            disT=disT+"0:00 - "+(nowHour)+":00";
                        }
                    }
                    b.time = disT;

                    list1_steps.add(b);
                    LogUtils.i(TAG,"_6Steps > 0 list1_steps集合添加了"+b.toString());
                }
                if (_12Steps > 0) {
                    StepOneHourInfoAdapterBean b = new StepOneHourInfoAdapterBean();
                    b.steps = _12Steps;
                    b.distances = _12Steps * stride;
                    b.carul = NumUtils.numBaoLiuWei0(_12Steps * stepCaruli);
                    String disT = tempTime;
                    if (lastHour >= 12){
                        disT=disT+" 6:00 - 12:00";
                    }else {
                        if (nowHour>=12){
                            disT=disT+" 6:00 - 12:00";
                        }else {
                            disT=disT+" 6:00 - "+(nowHour)+":00";
                        }
                    }
                    b.time = disT;
                    list1_steps.add(b);
                    LogUtils.i(TAG,"_12Steps > 0 list1_steps集合添加了"+b.toString());
                }
                if (_18Steps > 0) {
                    StepOneHourInfoAdapterBean b = new StepOneHourInfoAdapterBean();
                    b.steps = _18Steps;
                    b.distances = _18Steps * stride;
                    b.carul = NumUtils.numBaoLiuWei0(_18Steps * stepCaruli);
                    String disT = tempTime;
                    if (lastHour >= 18){
                        disT=disT+" 12:00 - 18:00";
                    }else {
                        if (nowHour>=18){
                            disT=disT+" 12:00 - 18:00";
                        }else {
                            disT=disT+" 12:00 - "+(nowHour)+":00";
                        }
                    }
                    b.time = disT;
                    list1_steps.add(b);
                    LogUtils.i(TAG,"_18Steps > 0 list1_steps集合添加了"+b.toString());
                }
                if (_24Steps > 0) {
                    StepOneHourInfoAdapterBean b = new StepOneHourInfoAdapterBean();
                    b.steps = _24Steps;
                    b.distances = _24Steps * stride;
                    b.carul = NumUtils.numBaoLiuWei0(_24Steps * stepCaruli);
                    String disT = tempTime;
                    disT=disT+" 18:00 - "+(nowHour)+":00";
                    b.time = disT;
                    list1_steps.add(b);
                    LogUtils.i(TAG,"_24Steps > 0 list1_steps集合添加了"+b.toString());
                }

                if (nowHour==0){
                    LogUtils.i(TAG, "nowHour = 0 执行了清空");
                    list1_steps.clear();
                }

                final BraTodayData braTodayData = new BraTodayData();
                braTodayData.list1 = list1_steps;

                braTodayData.list2 = list2_xl;
                braTodayData.maxHeart = maxHeart;
                braTodayData.minHeart = minHeart;
                braTodayData.avgHeart = avgHeart;

                braTodayData.list3 = list3_shm;
                braTodayData.deepSleepTotal = deepSleep;
                braTodayData.shallowSleepTotal = shallowSleep;
                braTodayData.sleeplessnessTotal = sleeplessness;
                if (starSleepTime < endSleepTime) {
                    braTodayData.starSleepTime = starSleepTime;
                    braTodayData.endSleepTime = endSleepTime;
                }


                post(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.i(TAG, "最终结果:" + braTodayData.toString());
                        if (mesuresCalBack != null) mesuresCalBack.SetBraTodayData(braTodayData);
                    }
                });


            }
        });


    }


    private int getLastDatHour(List<BraDb> todayDbList){
        if (todayDbList==null||todayDbList.size()<=0) return 1;
        BraDb lastBra = todayDbList.get(todayDbList.size()-1);//拿到今天数据库里面的最后一条数据
        //1809110930
        int mod = (int) ((lastBra.timeStr/100)%100);
        LogUtils.i(TAG,"数据库中最后一条数据"+lastBra.toString()+ "--modHour = "+mod);
        return mod;

    }


    //切换设备
    public void switchingEquipment(ProductStyle productStyle) {
        if (curRunProductStyle == productStyle) {
            LogUtils.i(TAG, "当前运行的产品就是切换的产品 无需重新重新切换");
            return;
        }


        this.curRunProductStyle = productStyle;//记录一下当前需要连接的产品设备

        if (mBaseManager != null) {//如果切换之前就已经有设备了 先断开连接
            mBaseManager.disConnect();
        }

        mBaseManager = getProductManager(this.curRunProductStyle);//获取相对应的产品管理器 并设置连接回调器

        if (mBaseManager != null) {
            mBaseManager.setBlueConnectStationCallback(mConnectStationCallback);
        }

        disConnectDevice(false);//断开连接

        scanBlueDevices();//扫描设备

        startAutoCheck(8000);//开始自动检测
    }


    //根据产品号获取相对应的产品管理器
    private BaseManager getProductManager(ProductStyle curRunProductStyle) {

        BaseManager baseManager = null;
        if (curRunProductStyle == ProductStyle.SCALE) {
            baseManager = mScaleManager;
        } else if (curRunProductStyle == ProductStyle.BPM) {
            baseManager = mBpmManager;
        } else if (curRunProductStyle == ProductStyle.TEMPERATURE) {
            baseManager = new TemperatureManager(mContext);
        } else if (curRunProductStyle == ProductStyle.EAR_THERMOMETER) {
            baseManager = mEarTemperatureManager;
        } else if (curRunProductStyle == ProductStyle.BLOODOXYGEN) {
            baseManager = mBOManager;
        } else if (curRunProductStyle == ProductStyle.BRACELET) {
            baseManager = mBracetManager;
        } else if (curRunProductStyle == ProductStyle.THREE_IN_ONE) {
            baseManager = mThreeOneManager;
        }

        return baseManager;
    }


    //扫描蓝牙设备
    private void scanBlueDevices() {
        if (mBlueScan != null) {

            long nextScanTime;
            if (mBlueScan.isScaningFlag){
                mBlueScan.stopScanBluetoothDevices();//先停止扫描
                nextScanTime = 1000;
            }else {
                nextScanTime = 0;
            }
            sendEmptyMessageDelayed(WHAT_START_SCAN,nextScanTime);
        }
    }


    //扫描回调器
    private IScanCallback mScanCallback = new IScanCallback() {
        @Override
        public void beforeScan() {
            LogUtils.i(TAG, "---beforeScan---");
           // device = null;
        }

        @Override
        public void scanOneDevice(final BluetoothDevice device, int rssi, byte[] scanRecord) {

                post(new Runnable() {
                    @Override
                    public void run() {
                        recordScanDevice(device);
                    }
                });
        }

        @Override
        public void overScan() {
            LogUtils.i(TAG, "---扫描结束---");
//            if (device == null&&!isOtaUpdate) {
//                //说明没有扫描成功 需要重新扫描
//                LogUtils.i(TAG, "---扫描结束 device = null 需要重新扫描");
//                removeMessages(WHAT_RESTART_SCAN);
//                sendEmptyMessageDelayed(WHAT_RESTART_SCAN, 8000);
//            }
        }
    };


    private static final int WHAT_RESTART_SCAN = 1;
    private static final int WHAT_AUTO_CHECK = 2;
    private static final int what_GetShH_RealTime_data = 3;
    private static final int WHAT_START_SCAN = 4;

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        if (msg.what == WHAT_RESTART_SCAN) {
            LogUtils.i(TAG, "---收到重新扫描的指令");
            scanBlueDevices();
        } else if (msg.what == WHAT_AUTO_CHECK) {
            removeMessages(WHAT_AUTO_CHECK);
            sendEmptyMessageDelayed(WHAT_AUTO_CHECK, 8000);
            autoCheck();
        } else if (msg.what == what_GetShH_RealTime_data) {
            if (mBracetManager != null) mBracetManager.getLiveData();
            sendEmptyMessageDelayed(what_GetShH_RealTime_data, 2000);
        }else if (msg.what == WHAT_START_SCAN){
            LogUtils.i(TAG, "--handleMsg-收到扫描的指令");
            if (mBlueScan!=null){
                mBlueScan.startScanBluetoothDevices(mScanCallback);//开始扫描
            }
        }


    }


    public void startAutoCheck(long delayMillis) {
        LogUtils.i(TAG,"--------startAutoCheck = delayMillis="+delayMillis);
        removeMessages(WHAT_AUTO_CHECK);
        sendEmptyMessageDelayed(WHAT_AUTO_CHECK, delayMillis);
    }

    public void stopAutoCheck() {
        LogUtils.i(TAG,"--------stopAutoCheck ");
        removeMessages(WHAT_AUTO_CHECK);
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();//停止扫描
        }
    }


    //自动检测机制
    private void autoCheck() {


        LogUtils.i(TAG, "---自动检测机制正在运行--autoCheck（）");



        if (mBaseManager == null) {
            LogUtils.i(TAG, "自动检测 mBaseManager = null 此次 return");
            return;
        }

        if (mBaseManager.isConnect()) {
            LogUtils.i(TAG, "自动检测 设备--已经连接 此次return");
            return;
        }

        if (mBlueScan != null) {
            if (mBlueScan.isScaningFlag){
                LogUtils.i(TAG,"自动检测 扫描器正在扫描中 此次退出");
                //stopScan();
                return;
            }
            //能执行到这里 说明 设备没有连接中 并且没有扫描中
            LogUtils.i(TAG, "自动检测 设备没有连接中 准备重新扫描");
          //  restartInitBlueScan();
            scanBlueDevices();
        }


    }


    //连接回调器
    private IConnectStationCallback mConnectStationCallback = new IConnectStationCallback() {
        @Override
        public void onConnected(ProductStyle productStyle, BluetoothDevice device) {
            if(device==null)return;
            String name = device.getName();
            String address = device.getAddress();

            LogUtils.i(TAG, productStyle.getProductName() + "--连接成功--onConnected--device.name = " + name + "---device.address = " + address);


            if (productStyle == ProductStyle.SCALE) {//如果此时连接着的是体脂秤 把连接着的蓝牙名字传递给ScaleUser 它下发用户信息时比较好兼容-B
                ScaleUser.currentConnectScaleBlueName = name;
               // if (mScaleManager!=null)mScaleManager.setSleepDisconnectTime();
            }

            if (productStyle == ProductStyle.BPM && mBpmManager != null) {
                mBpmManager.setConnectName(device.getName());

            }
            if (productStyle == ProductStyle.BRACELET && mBracetManager != null) {
                mBracetManager.setConnectDevice(device);

            }


            if (productStyle != ProductStyle.BRACELET) {
                CommonEventBus commonEventBus = new CommonEventBus(EhcManager.TAG, "MainActivity", 2, "关闭同步历史数据框");
                EventBus.getDefault().post(commonEventBus);
            }

            //血氧设备连接成功以后需要发送指令设备才会发送回信息回来----这个比较特殊
            if (productStyle == ProductStyle.BLOODOXYGEN && mBOManager != null && mBOManager == mBaseManager) {
                LogUtils.i(TAG, "血氧----已经连接成功");
                mBOManager.starSendCmd();
            } else if (productStyle == ProductStyle.BRACELET && mBracetManager != null && mBracetManager == mBaseManager) {
                //此时连接的是手环

                mBracetManager.sysDeviceTime();//手环连接成功的第一步:同步一下设备时间

                //sendBraUserInfo();
            }

            if (mesuresCalBack != null) mesuresCalBack.onConnected(productStyle, device);


            stopScan();


        }

        @Override
        public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {
            if (mesuresCalBack != null) mesuresCalBack.onConnecting(productStyle, device);
        }

        @Override
        public void onDisConnected(ProductStyle productStyle) {
            LogUtils.i(TAG, productStyle.getProductName() + "-------------连接断开");

            if (productStyle == ProductStyle.BRACELET) {
                //如果断开的是手环 终止手滑的实时获取数据
                removeMessages(what_GetShH_RealTime_data);

                if (mBracetManager != null) {
                    if (mBracetManager.mBraceletBytesAnalysis != null) {
                        mBracetManager.mBraceletBytesAnalysis.bytes = new byte[0];
                    }
                    mBracetManager.isSysingHisDataFinish = false;
                    //  mBracetManager.isOpenRealTimeRate=false;
                }
                CommonEventBus commonEventBus = new CommonEventBus(EhcManager.TAG, "MainActivity", 2, "关闭同步历史数据框");
                EventBus.getDefault().post(commonEventBus);
            } else if (productStyle == ProductStyle.THREE_IN_ONE) {
                if (mThreeOneManager != null) mThreeOneManager.clear();
            }

            if (mesuresCalBack != null) mesuresCalBack.onDisConnected(productStyle);

            if (!isOtaUpdate){
                removeMessages(WHAT_AUTO_CHECK);
                sendEmptyMessage(WHAT_AUTO_CHECK);//当连接断开的时候 开始检测
            }

        }
    };


    private void recordScanDevice(BluetoothDevice device) {
        if (device == null) {
            return;
        }
        String name = device.getName();
        String address = device.getAddress();
        LogUtils.i(TAG, "扫描到设备--Name = " + name + "---Addrss = " + address);
        if (TextUtils.isEmpty(name)||TextUtils.isEmpty(address)){
            return;
        }





        String productBlueName = this.curRunProductStyle.getBlueName();//获取当前需要连接的蓝牙名字


        //EE:86:1F:1F:A2:00
        //EE:86:1F:1F:29:CB
        if (name.contains(productBlueName)
                || (productBlueName.contains(name) && curRunProductStyle == ProductStyle.SCALE)
                || (productBlueName.contains(name) && curRunProductStyle == ProductStyle.BPM)
                || (name.contains(productBlueName) && curRunProductStyle == ProductStyle.THREE_IN_ONE)
                || ("LTYH".equals(name) && curRunProductStyle == ProductStyle.BRACELET)) {
            LogUtils.i(TAG, "--找到了需要连接的蓝牙设备------Name = " + name + "---Addrss = " + address + "---准备连接---");
           // this.device = device;


            startAutoCheck(8000);//停止检测 8秒后再去检测 怕没连接上检测又来了 重新开始扫描连接了

            if (mBlueScan != null) {

                mBlueScan.exitScan();
            }//退出扫描


            connectBluetooth(device);//开始连接设备


        }
    }


    //连接蓝牙设备
    private void connectBluetooth(String address) {
        if (mBaseManager != null) {
            mBaseManager.connectDevice(address);
        }
    }

    //连接蓝牙设备
    private void connectBluetooth(BluetoothDevice bluetoothDevice) {
        if (mBaseManager != null) {
            mBaseManager.connectDevice(bluetoothDevice);
        }
    }

    //断开连接 sendFront是否发给给前端的意思
    public void disConnectDevice(boolean sendFront) {
        if (mBaseManager != null) mBaseManager.disConnect(sendFront);
    }


    public void stopScan() {
        if (mBlueScan != null) {
            mBlueScan.stopScanBluetoothDevices();
        }
    }

    private AMesuresCalBack mesuresCalBack;

    public void setMesuresCalBack(AMesuresCalBack mesuresCalBack) {
        this.mesuresCalBack = mesuresCalBack;
    }


    //手环里面的Viewpage的position已经改变
    public void braPageSelectedChange(int position) {
        if (mBracetManager == null) {
            return;
        }
        if (mBracetManager.isConnect() && mBracetManager.isSysingHisDataFinish) {//此时手环正在连接着并且手环已经同步完历史数据了
            stopJianTingShHData();
            if (position == 0 || position == 2) {
                mBracetManager.getHeartRate(false);
            } else if (position == 1) {
                mBracetManager.getHeartRate(true);
            }
            if (position == 0) {
                startJianTingShHData();
            }
        }
    }

    //设置手环心率周期时间
    public void setBraXlZhq(int min) {
        if (mBracetManager != null) mBracetManager.setHeartCycle(min);
    }


//    用户信息:男 1992-12-01 180cm 51.3kg
//
//    步幅 (0.415*180)/100  = 0.747 m/step
//    步卡 (51.3-15)*0.000693+0.005895 = 0.0310509 kcal/step
//
//    2517步
//    2517里程 2517*0.747 = 1880.199 m  ----> 1.88 km
//    2517卡路里 2517*0.0310509 = 78.1551153 kcal ----->问题1:这里怎么会返回来的卡路里是错误的?手环实时返回来的卡路里是77kcal 这里按照公式计算出来的是78kcal
//
//    162步
//    162里程 162*0.747 = 121.014 m  ----> 0.12 km
//    162卡路里 162*0.0310509 = 5.0302458kcal
//
//    2355步
//    2355里程 2355*0.747 = 1759.185 m  ----> 1.75 km (这里我收到你们的意思是向下取整)  问题2:向下取整得出来的数据对不上 1.75+0.12=1.87   1.87不等于1.88
//    2355卡路里 2355*0.0310509 = 73.143945 kcal  问题3:5+73=78 78怎么会大于手环实时返回来的77kcal？


    public void getShHVersion(){
        if (mBracetManager!=null&&mBracetManager.isConnect()){
            mBracetManager.getVersion();
        }
    }

}
